package pack0903;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class DemoA {
    public static void main(String[] args) {
        new UPDS().start();
        new UPDC().start();
    }
}
class UPDS extends Thread{
    @Override
    public void run() {
       try {
           //1.创建服务器端 DatagramSocket ，指定端口
           DatagramSocket socket = new DatagramSocket(9999);
           //2.创建数据包 用于接收客户端发送的数据
           byte[] bytes = new byte[1024];//创建字节数组，指定接收的数据包的大小
           DatagramPacket packet = new DatagramPacket(bytes,bytes.length);
           //3.接收客户端发送的数据
           System.out.println("客户端已启动，等待用户发送数据");
           socket.receive(packet);//此方法在接收到数据之前会一直阻塞
           //4.读取数据
           String info = new String(bytes,0,packet.getLength());//创建字符串对象
           System.out.println("我是服务器，客户端说："+info);
       }catch (Exception e){
           System.out.println(e.getMessage());
       }
    }
}
class UPDC extends Thread{
    @Override
    public void run() {
        try {
            //1.定义服务器的地址，端口号，数据
            InetAddress address = InetAddress.getByName("localhost");
            byte[] bytes = "Hello".getBytes();
            //2.创建数据包
            DatagramPacket packet = new DatagramPacket(bytes,bytes.length,address,9999);
            //含发送的数据信息
            DatagramSocket socket = new DatagramSocket();//3.创建 DatagramSocket 对象
            socket.send(packet);//4.向服务器端发送数据包
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
}

